package com.longtop.framework.sys.file.supports;

import java.io.File;
import java.io.IOException;

import com.longtop.framework.util.StringUtil;
import com.oreilly.servlet.multipart.FileRenamePolicy;

/**
 * 
 */
public abstract class BaseFileRename implements FileRenamePolicy {
	/**
	 * 需要后缀
	 */
	protected boolean needSuffix = true;

	/**
	 * 需要混淆上传文件名(当重名的时候)
	 */
	protected boolean needConfusionFileName = false;

	/**
	 * 所有文件都混淆
	 */
	protected boolean allConfusionFileName = false;

	protected abstract String createName(String name);

	protected String createFileName(String name) {
		String filename = StringUtil.getString(name);
		if (needConfusionFileName || allConfusionFileName) {
			return createName(name);
		}
		return filename;
	}

	public File rename(File f) {
		if (allConfusionFileName) {

		} else {
			if (createNewFile(f)) {
				return f;
			}
		}

		String name = f.getName();
		String body = null;
		String ext = null;

		int dot = name.lastIndexOf(".");
		if (dot != -1 && needSuffix) {
			body = createFileName(name.substring(0, dot));
			ext = name.substring(dot);
		} else {
			body = createFileName(name);
			ext = "";
		}

		boolean bool = false;
		if (allConfusionFileName) {
			bool = true;
		} else {
			bool = !createNewFile(f);
		}
		int count = 0;
		while (bool && count < 10000) {
			count++;
			String newName = body + count + ext;
			f = new File(f.getParent(), newName);
		}

		return f;
	}

	private boolean createNewFile(File f) {
		try {
			return f.createNewFile();
		} catch (IOException ignored) {
			return false;
		}
	}

	public void setNeedSuffix(boolean needSuffix) {
		this.needSuffix = needSuffix;
	}

	public void setNeedConfusionFileName(boolean needConfusionFileName) {
		this.needConfusionFileName = needConfusionFileName;
	}

	public void setAllConfusionFileName(boolean allConfusionFileName) {
		this.allConfusionFileName = allConfusionFileName;
	}
}
